package com.elbis.business.manager;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.elbis.action.input.ErrorMessages;
import com.elbis.business.entity.messages.ErrorMessage;
import com.elbis.business.entity.messages.InformativeMessage;
import com.elbis.util.HibernateUtil;

/**
 * Used for error and informative messages displayed to end user.
 * 
 * @author cc
 * 
 */
public class MessageManager {

	private MessageManager() {
	}

	private static final Logger logger = Logger.getLogger(MessageManager.class);

	public static ErrorMessage getErrorMessage(Integer number) {
		return getErrorMessage(number, ErrorMessages.DEFAULT_MESSAGE_LANGUAGE);
	}

	public static ErrorMessage getErrorMessage(Integer number, String language) {
		Session session = HibernateUtil.getSession();
		ErrorMessage message = null;
		try {
			message = (ErrorMessage) session
					.createCriteria(ErrorMessage.class)
					.add(Restrictions.and(Restrictions.eq("number", number),
							Restrictions.eq("language", language)))
					.uniqueResult();
			if (message == null) {
				message = (ErrorMessage) session
						.createCriteria(ErrorMessage.class)
						.add(Restrictions.and(
								Restrictions.eq("number", number),
								Restrictions.eq("language",
										ErrorMessages.DEFAULT_MESSAGE_LANGUAGE)))
						.uniqueResult();
			}
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return message;
	}

	public static InformativeMessage getInformativeMessage(Integer number) {
		return getInformativeMessage(number,
				ErrorMessages.DEFAULT_MESSAGE_LANGUAGE);
	}

	public static InformativeMessage getInformativeMessage(Integer number,
			String language) {
		Session session = HibernateUtil.getSession();
		InformativeMessage message = null;
		try {
			message = (InformativeMessage) session
					.createCriteria(InformativeMessage.class)
					.add(Restrictions.and(Restrictions.eq("number", number),
							Restrictions.eq("language", language)))
					.uniqueResult();
			if (message == null) {
				message = (InformativeMessage) session
						.createCriteria(InformativeMessage.class)
						.add(Restrictions.and(
								Restrictions.eq("number", number),
								Restrictions.eq("language",
										ErrorMessages.DEFAULT_MESSAGE_LANGUAGE)))
						.uniqueResult();
			}
		} catch (HibernateException e) {
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return message;
	}

}
